<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <el-row v-show="showSearch">
        <el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">
          <el-form-item label="模块" prop="moduleId">
            <el-select v-model="state.queryForm.moduleId" placeholder="请选择模块" clearable>
              <el-option :label="moduleInfo.name" :value="moduleInfo.id"
                         v-for="moduleInfo in moduleInfoList "></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="分支" prop="branchId">
            <el-select v-model="state.queryForm.branchId" placeholder="请选择分支" clearable>
              <el-option :label="branchInfo.name" :value="branchInfo.id"
                         v-for="branchInfo in branchInfoList "></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="容器名" prop="containerName">
            <el-input placeholder="请输入容器名" v-model="state.queryForm.containerName"/>
          </el-form-item>
          <el-form-item label="服务器ip" prop="serverIp">
            <el-input placeholder="请输入服务器ip" v-model="state.queryForm.serverIp"/>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="state.queryForm.status" placeholder="请选择状态" clearable>
              <el-option :label="item.label" :value="item.value" v-for="(item, index) in docker_info_status"
                         :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button icon="search" type="primary" @click="getDataList">
              查询
            </el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <el-row>
        <div class="mb8" style="width: 100%">
          <el-button icon="folder-add" type="primary" class="ml10" @click="formDialogRef.openDialog()"
                     v-auth="'deploy_dockerInfo_active'">
            激 活
          </el-button>
          <!--          <el-button plain :disabled="multiple" icon="Delete" type="primary"-->
          <!--                     v-auth="'deploy_dockerInfo_del'" @click="handleDelete(selectObjs)">-->
          <!--            删除-->
          <!--          </el-button>-->
          <right-toolbar v-model:showSearch="showSearch" :export="'deploy_dockerInfo_export'"
                         @exportExcel="exportExcel" class="ml10 mr20" style="float: right;"
                         @queryTable="getDataList"></right-toolbar>
        </div>
      </el-row>
      <el-table :data="state.dataList" v-loading="state.loading" border
                :cell-style="tableStyle.cellStyle" :header-cell-style="tableStyle.headerCellStyle"
                @selection-change="selectionChangHandle"
                @sort-change="sortChangeHandle">
        <el-table-column type="selection" width="40" align="center"/>
        <el-table-column type="index" label="#" width="40"/>
        <el-table-column prop="containerId" label="容器id" show-overflow-tooltip/>
        <el-table-column prop="moduleName" label="模块" show-overflow-tooltip/>
        <el-table-column prop="branchName" label="分支" show-overflow-tooltip/>
        <el-table-column prop="containerName" label="容器名" show-overflow-tooltip/>
        <el-table-column prop="configJson" label="配置json" show-overflow-tooltip/>
        <el-table-column prop="serverIp" label="服务器ip" show-overflow-tooltip/>
        <el-table-column prop="outServerPort" label="容器对外端口" show-overflow-tooltip/>
        <el-table-column prop="innerServerPort" label="容器内部端口" show-overflow-tooltip/>
        <el-table-column prop="status" label="状态" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="docker_info_status" :value="scope.row.status"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updatetime" label="更新时间" show-overflow-tooltip/>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button icon="Monitor" text type="info" size="small" v-auth="'deploy_dockerInfo_log'"
                       @click="formDialogRef.openDialog(scope.row.id)">日志
            </el-button>
            <el-button icon="VideoPause" text type="warning" size="small" v-auth="'deploy_dockerInfo_stop'"
                       v-if="scope.row.status === 0"
                       @click="handleStopDockerInfo(scope.row.id)">停止
            </el-button>
            <el-button icon="VideoPlay" text type="success" size="small" v-auth="'deploy_dockerInfo_start'"
                       v-if="scope.row.status === 1"
                       @click="handleStartDockerInfo(scope.row.id)">启用
            </el-button>
            <el-button icon="edit-pen" text type="danger" v-auth="'deploy_dockerInfo_remove'"
                       v-if="scope.row.status === 1"
                       @click="handleRemoveDockerInfo(scope.row.id)">废弃
            </el-button>

            <el-button icon="edit-pen" text type="primary" v-auth="'deploy_dockerInfo_edit'"
                       v-if="scope.row.status === 2"
                       @click="formDialogRef.openDialog(scope.row.id)">编辑
            </el-button>
            <el-button icon="edit-pen" text type="primary" v-auth="'deploy_dockerInfo_reborn'"
                       v-if="scope.row.status === 2"
                       @click="handleRebornDockerInfo(scope.row.id)">复活
            </el-button>
            <el-button icon="edit-pen" text type="primary" v-auth="'deploy_dockerInfo_copy'"
                       @click="copyDialogRef.openDialog(scope.row)">复制
            </el-button>
            <el-button icon="edit-pen" text type="primary" v-auth="'deploy_dockerInfo_clean'"
                       v-if="scope.row.status === 2"
                       @click="handleCleanDockerInfo(scope.row.id)">清除
            </el-button>
            <el-button icon="edit-pen" text type="primary" v-auth="'deploy_dockerInfo_upgrade'"
                       @click="handleUpgradeDockerInfo(scope.row.id)">升级
            </el-button>
            <!--            <el-button icon="delete" text type="primary" v-auth="'deploy_dockerInfo_del'"-->
            <!--                       @click="handleDelete([scope.row.id])">删除-->
            <!--            </el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination"/>
    </div>

    <!-- 编辑、新增  -->
    <form-dialog ref="formDialogRef" @refresh="getDataList(false)"/>
    <copy-dialog ref="copyDialogRef" @refresh="getDataList(false)"/>
    <upgrade-dialog ref="upgradeDialogRef" @refresh="getDataList(false)"/>
    <!-- 添加 loading 对话框 -->
    <!-- 修改对话框内容部分 -->
    <el-dialog
        :title="loadingDialog.title"
        v-model="loadingDialog.visible"
        width="30%"
        :close-on-click-modal="false"
        :show-close="false"
        center>
      <div style="display: flex; align-items: center; justify-content: center;">
        <el-icon class="is-loading" size="24">
          <Loading/>
        </el-icon>
        <span style="margin-left: 10px;">{{ loadingDialog.message }}</span>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="deployDeplDockerInfo">
import {BasicTableProps, useTable} from "/@/hooks/table";
import {fetchList, remove, start, stop, clean, reborn} from "/@/api/bms/deploy/dockerInfo";
import {listAllModuleInfo} from "/@/api/bms/deploy/moduleInfo";
import {listAllBranchInfo} from "/@/api/bms/deploy/branchInfo";
import {useMessage, useMessageBox} from "/@/hooks/message";
import {useDict} from '/@/hooks/dict';
import {ElMessageBox} from 'element-plus'
// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
// 引入组件
const CopyDialog = defineAsyncComponent(() => import('./copy.vue'));
// 引入组件
const UpgradeDialog = defineAsyncComponent(() => import('./upgrade.vue'));



// 定义查询字典
const {docker_info_status} = useDict('docker_info_status')
// 定义变量内容
const formDialogRef = ref()
const copyDialogRef = ref()
const upgradeDialogRef = ref()
// 搜索变量
const queryRef = ref()
const showSearch = ref(true)
// 多选变量
const selectObjs = ref([]) as any
const multiple = ref(true)

const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {},
  pageList: fetchList
})

//  table hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  downBlobFile,
  tableStyle
} = useTable(state)

// 清空搜索条件
const resetQuery = () => {
  // 清空搜索条件
  queryRef.value?.resetFields()
  // 清空多选
  selectObjs.value = []
  getDataList()
}

// 导出excel
const exportExcel = () => {
  downBlobFile('/bms/deploy/dockerInfo/export', Object.assign(state.queryForm, {ids: selectObjs}), 'dockerInfo.xlsx')
}

// 多选事件
const selectionChangHandle = (objs: { id: string }[]) => {
  selectObjs.value = objs.map(({id}) => id);
  multiple.value = !objs.length;
};

// 删除操作
// const handleDelete = async (ids: string[]) => {
//   try {
//     await useMessageBox().confirm('此操作将永久删除');
//   } catch {
//     return;
//   }
//
//   try {
//     await delObjs(ids);
//     getDataList();
//     useMessage().success('删除成功');
//   } catch (err: any) {
//     useMessage().error(err.msg);
//   }
// };

//加载所有模块信息
const moduleInfoList = ref([])  // 模块信息列表
const loadModuleInfoList = async () => {
  const res = await listAllModuleInfo()
  moduleInfoList.value = res.data
  console.log("moduleInfoList", moduleInfoList.value)
}
loadModuleInfoList()

//加载所有分支信息
const branchInfoList = ref([])  // 分支信息列表
const loadBranchInfoList = async () => {
  const res = await listAllBranchInfo()
  branchInfoList.value = res.data
  console.log("branchInfoList", branchInfoList.value)
}
loadBranchInfoList()

//停止容器
const handleStopDockerInfo = async (id) => {
  console.log("handleStopDockerInfo", id)

  // 执行停止操作
  ElMessageBox.confirm('确定要停止该容器吗?')
      .then(async () => {
        try {
          loadingDialog.title = '操作中';
          loadingDialog.message = '正在停止容器...';
          loadingDialog.visible = true;
          let res = await stop(id)
          console.log("handleStopDockerInfo---res", res)
          if (res.data) {
            useMessage().success('停止成功');
            getDataList()

          }
        }catch (error) {
          console.error('Error stopping container:', error);
        }finally {
          loadingDialog.visible = false;
        }

      })
      .catch(() => {
        // catch error
      })


}

//启动容器
const handleStartDockerInfo = async (id) => {
  console.log("handleStartDockerInfo", id)

  ElMessageBox.confirm('确定要启动该容器吗?')
      .then(async () => {

        try {
          loadingDialog.title = '操作中';
          loadingDialog.message = '正在启动容器...';
          loadingDialog.visible = true;
          let res = await start(id)
          console.log("handleStopDockerInfo---res", res)
          if (res.data) {
            useMessage().success('启动成功');
            getDataList()
          }
        }catch (error) {
          console.error('Error stopping container:', error);
        }finally {
          loadingDialog.visible = false;
        }



      })
      .catch(() => {
        // catch error
      })

}

//废弃容器
const handleRemoveDockerInfo = async (id) => {
  console.log("handleRemoveDockerInfo", id)

  ElMessageBox.confirm('确定要废弃该容器吗?')
      .then(async () => {


        try {
          loadingDialog.title = '操作中';
          loadingDialog.message = '正在废弃容器...';
          loadingDialog.visible = true;
          let res = await remove(id)
          console.log("handleRemoveDockerInfo---res", res)
          if (res.data) {
            useMessage().success('废弃成功');
            getDataList()
          }
        }catch (error) {
          console.error('Error stopping container:', error);
        }finally {
          loadingDialog.visible = false;
        }

      })
      .catch(() => {
        // catch error
      })

}
//清理容器
const handleCleanDockerInfo = async (id) => {
  console.log("handleCleanDockerInfo", id)

  ElMessageBox.confirm('确定要清理该容器吗?')
      .then(async () => {
        let res = await clean(id)
        console.log("handleCleanDockerInfo---res", res)
        if (res.data) {
          useMessage().success('清理成功');
          getDataList()
        }
      })
      .catch(() => {
        // catch error
      })

}
// 复活容器
const handleRebornDockerInfo = async (id) => {
  console.log("handleRebornDockerInfo", id)

  ElMessageBox.confirm('确定要复活该容器吗?')
      .then(async () => {


        try {
          loadingDialog.title = '操作中';
          loadingDialog.message = '正在复活容器...';
          loadingDialog.visible = true;
          let res = await reborn(id)
          console.log("handleRebornDockerInfo---res", res)
          if (res.data) {
            useMessage().success('复活成功');
            getDataList()
          }

        }catch (error) {
          console.error('Error stopping container:', error);
        }finally {
          loadingDialog.visible = false;
        }

      })
      .catch(() => {
        // catch error
      })

}
const handleUpgradeDockerInfo = async (id) => {
  console.log("handleUpgradeDockerInfo", id)

  upgradeDialogRef.value.openDialog(id)  // 打开分支选择弹窗
}




const loadingDialog = reactive({
  visible: false,
  title: '',
  message: ''
});

</script>
